package com.example.springboottools.pic;

import javax.imageio.ImageIO;
import javax.sql.DataSource;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PicHtml {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService poolExecutor = new ThreadPoolExecutor(
                16,
                Runtime.getRuntime().availableProcessors() * 2,
                1,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(3010)
        );

        DataSource dataSource = DataSourceConfig.getDataSource();
        for (int j = 0; j < 3000; j++) {
            String sql = "SELECT UUID, HTML_URL, SKU FROM ZTEMP_SKU_HTML_RUN zshr WHERE RUN_STATUS = '0' AND rownum < 100";
            try (Connection connection = dataSource.getConnection();
                 PreparedStatement ps = connection.prepareStatement(sql);
                 ResultSet rs = ps.executeQuery()) {

                List<Map<String, String>> maps = new ArrayList<>();
                StringBuffer sb = new StringBuffer();
                if (!rs.next()) {
                    continue;
                }
                do {
                    Map<String, String> map = new HashMap<>();
                    String uuid = rs.getString("UUID");
                    String htmlUrl = rs.getString("HTML_URL");
                    String sku = rs.getString("SKU");
                    map.put("UUID", uuid);
                    map.put("HTML", htmlUrl);
                    map.put("SKU", sku);
                    maps.add(map);
                    sb.append("'").append(uuid).append("',");
                } while (rs.next());

                String updateSql1 = "UPDATE ZTEMP_SKU_HTML_RUN SET RUN_STATUS = '1' WHERE UUID IN (" + sb.substring(0, sb.length() - 1) + ")";
                try (PreparedStatement preparedStatement = connection.prepareStatement(updateSql1)) {
                    int i = preparedStatement.executeUpdate();
                    connection.commit();
                }

                poolExecutor.execute(() -> {
                    String threadName = Thread.currentThread().getName();
                    AtomicInteger i = new AtomicInteger();
                    maps.forEach(map -> {
                        String html = map.get("HTML");
                        String uuid = map.get("UUID");
                        String sku = map.get("SKU");
                        try {
                            List<String> imgSrc = getImgSrc(html);
                            int heightCount = 0;
                            List<String> _urlList = new ArrayList<>();
                            for (String _url : imgSrc) {
                                try {
                                    URL url = new URL(_url);
                                    BufferedImage image = ImageIO.read(url);
                                    int height = image.getHeight();
                                    heightCount += height;
                                    _urlList.add(_url);
                                } catch (Exception e) {
                                    System.out.println(String.format("SKU:%s,图片地址:%s,图片不存在", sku, _url));
                                }
                            }
                            String updateSql2 = "UPDATE ZTEMP_SKU_HTML_RUN SET RUN_STATUS = '2', HEIGTH = '" + heightCount + "', NUM = '" + _urlList.size() + "' WHERE UUID = '" + uuid + "'";
                            try (Connection conn = dataSource.getConnection();
                                 PreparedStatement preparedStatement1 = conn.prepareStatement(updateSql2)) {
                                int i2 = preparedStatement1.executeUpdate();
                                conn.commit();
                            }
                        } catch (Exception e) {
                            String updateSql3 = "UPDATE ZTEMP_SKU_HTML_RUN SET RUN_STATUS = '3' WHERE UUID = '" + uuid + "'";
                            try (Connection conn = dataSource.getConnection();
                                 PreparedStatement preparedStatement1 = conn.prepareStatement(updateSql3)) {
                                int i3 = preparedStatement1.executeUpdate();
                                conn.commit();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                        System.out.println(String.format("线程名称：%s,当前线程执行SKU数量：%s", threadName, i.getAndIncrement()));
                    });
                });

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        poolExecutor.shutdown();
        while (!poolExecutor.isTerminated()){
            TimeUnit.SECONDS.sleep(10);
            System.out.println("线程执行中,请勿关闭"+poolExecutor.isTerminated());
        }

    }
    public static List<String> getImgSrc(String content) {

        List<String> list = new ArrayList<String>();
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/>   <img alt="" src="1.jpg"></img>     <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);

                //开始匹配<img />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    String str_src = m_src.group(3);
                    if (!str_src.startsWith("http"))str_src="http:"+str_src;
                    list.add(str_src);
                }
                //结束匹配<img />标签中的src

                //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }
        return list;

    }
}
